package com.woniuxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.woniuxy.dto.GoodsPropDto;
import com.woniuxy.dto.MenusDto;
import com.woniuxy.dto.PropGroupAndPropDto;
import com.woniuxy.dto.commonDto.BaseDto;
import com.woniuxy.dto.GoodsPropGroupDto;
import com.woniuxy.entity.*;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.GoodsFiledException;
import com.woniuxy.mapper.GoodsPropgroupMapper;
import com.woniuxy.param.*;
import com.woniuxy.service.GoodsPropService;
import com.woniuxy.service.GoodsPropgroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.GoodsSmallService;
import com.woniuxy.service.GoodsSmallerService;
import com.woniuxy.util.WoniuBeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性组 服务实现类
 * </p>
 *
 * @author zcx, ftl, gr, rhs
 * @since 2022-01-04
 */
@Service
public class GoodsPropgroupServiceImpl extends ServiceImpl<GoodsPropgroupMapper, GoodsPropgroup> implements GoodsPropgroupService {

    @Resource
    private GoodsSmallService goodsSmallService;

    @Resource
    private GoodsSmallerService service;

    @Resource
    private GoodsPropService goodsPropService;

    @Override
    public BaseDto<GoodsPropGroupDto> listGoodsPropGroup(PageQueryParam<String> pqp) {
        QueryWrapper<GoodsPropGroupDto> query = new QueryWrapper<>();
        if (!StringUtils.isEmpty(pqp.getQueryCriteria())) {
            query.and(wrapper -> wrapper
                    .like("t1.goods_propgroup_name", pqp.getQueryCriteria())
                    .or()
                    .like("t1.goods_small_name", pqp.getQueryCriteria())
            );
        }
        query.ne("t1.goods_propgroup_status", 2);
        BaseDto<GoodsPropGroupDto> baseDto = new BaseDto<>();
        Page<GoodsPropGroupDto> page = (Page<GoodsPropGroupDto>) this.baseMapper.listGoodsPropGroup(new Page<>(pqp.getIndexPage(), pqp.getPageSize()), query);
        baseDto.setIndexPage(page.getCurrent());
        baseDto.setList(page.getRecords());
        baseDto.setPageCount(page.getPages());
        //判断是否有上一页
        baseDto.setHasPrevious(page.hasPrevious());
        //判断是否有下一页
        baseDto.setHasNext(page.hasNext());
        baseDto.setTotal(page.getTotal());
        return baseDto;
    }


    @Override
    public List<PropGroupAndPropDto> listGoodsPropGroups(Integer goodsSmallerId) {
        List<GoodsPropgroup> list = list(new QueryWrapper<GoodsPropgroup>().eq("goods_propgroup_status", 0).eq("goods_smaller_id", goodsSmallerId));
        List<GoodsProp> props = goodsPropService.list(new QueryWrapper<GoodsProp>().eq("goods_prop_del", 0));

        Map<Integer, PropGroupAndPropDto> maps = new HashMap<>();

        List<PropGroupAndPropDto> mds = new ArrayList<>();
        for (GoodsPropgroup goodsPropgroup : list) {
            PropGroupAndPropDto dto = WoniuBeanUtils.copyObject(goodsPropgroup, PropGroupAndPropDto.class);
            mds.add(dto);
            maps.put(dto.getGoodsPropgroupId(), dto);
        }

        for (GoodsProp prop : props) {
            PropGroupAndPropDto propGroupAndPropDto = maps.get(prop.getGoodsPropgroupId());
            if (!StringUtils.isEmpty(propGroupAndPropDto)) {
                propGroupAndPropDto.setList(propGroupAndPropDto.getList() == null ? new ArrayList<GoodsPropDto>() : propGroupAndPropDto.getList());
                GoodsPropDto dto = WoniuBeanUtils.copyObject(prop, GoodsPropDto.class);
                String select = prop.getGoodsPropSelect();
                Gson gson = new Gson();
                String[] strings = gson.fromJson(select, String[].class);
                dto.setSelect(strings);
                propGroupAndPropDto.getList().add(dto);

            }

        }
        return mds;
    }


    @Override
    public List<GoodsPropDto> listGoodsProps(Integer goodsSmallerId) {
        List<GoodsPropgroup> list = list(new QueryWrapper<GoodsPropgroup>().eq("goods_propgroup_status", 0).eq("goods_smaller_id", goodsSmallerId));
        if (null == list || list.size() == 0) {
            return null;
        }
        List<Integer> collect = list.stream().map(
                id -> id.getGoodsPropgroupId()
        ).collect(Collectors.toList());

        List<GoodsProp> props = goodsPropService.list(new QueryWrapper<GoodsProp>().eq("goods_prop_del", 0).in("goods_propgroup_id", collect));
        List<GoodsPropDto> dtos = WoniuBeanUtils.copyList(props, GoodsPropDto.class);
        for (GoodsPropDto dto : dtos) {
            String select = dto.getGoodsPropSelect();
            Gson gson = new Gson();
            String[] strings = gson.fromJson(select, String[].class);
            dto.setSelect(strings);
        }

        return dtos;
    }


    @Override
    public GoodsPropGroupDto findGoodsPropGroupById(Integer id) {
        GoodsPropgroup propgroup = getOne(new QueryWrapper<GoodsPropgroup>().eq("goods_propgroup_id", id).ne("goods_propgroup_status", 3));
        return WoniuBeanUtils.copyObject(propgroup, GoodsPropGroupDto.class);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveGoodsPropGroups(SaveGoodsPropgroupParam sgpp) {
        //一个三级类只能添加一个属性组
        List<GoodsSmaller> list = service.listByIds(sgpp.getGoodsSmallerIds());

        if (null != list && list.size() > 0) {
            for (GoodsSmaller goodsSmaller : list) {
                List<GoodsPropgroup> propgroups = list(new QueryWrapper<GoodsPropgroup>().ne("goods_propgroup_status", 2).eq("goods_smaller_id", goodsSmaller.getGoodsSmallId()));
                if (propgroups.size() >= 1) {
                    throw new GoodsFiledException(CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_2.getMessage(), CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_2.getCode());
                }
            }
        }


        if (sgpp.getGoodsSmallerIds().size() != list.size()) {
            throw new GoodsFiledException(CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_1.getMessage(), CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_1.getCode());
        }
        ArrayList<GoodsPropgroup> propGroups = new ArrayList<>();
        for (GoodsSmaller goodsSmaller : list) {
            GoodsPropgroup goodsPropgroup = new GoodsPropgroup();
            goodsPropgroup.setGoodsPropgroupName(sgpp.getGoodsPropgroupName());
            goodsPropgroup.setGoodsPropgroupStatus(sgpp.getGoodsPropgroupStatus());
            goodsPropgroup.setGoodsSmallerId(goodsSmaller.getGoodsSmallerId());
            goodsPropgroup.setGoodsSmallerName(goodsSmaller.getGoodsSmallerName());
            propGroups.add(goodsPropgroup);
        }


        return saveBatch(propGroups);
    }

    @Override
    public boolean updateGoodsPropGroup(UpdateGoodsPropgroupParam ugpp) {
         GoodsSmaller one = service.getOne(new QueryWrapper<GoodsSmaller>().eq("goods_smaller_id", ugpp.getGoodsSmallerId())
                .ne("goods_smaller_status", 2));
        if (StringUtils.isEmpty(one))
            throw new GoodsFiledException(CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_1.getMessage(), CodeEnum.GOODS_PROP_GROUP_SAVE_FAIL_1.getCode());

        GoodsPropgroup propgroup = WoniuBeanUtils.copyObject(ugpp, GoodsPropgroup.class);
        propgroup.setGoodsSmallerName(one.getGoodsSmallerName());
        return updateById(propgroup);
    }

    @Override
    public boolean removePropGroupByIds(List<Integer> ids) {
        List<GoodsPropgroup> list = list(new QueryWrapper<GoodsPropgroup>()
                .in("goods_propgroup_id", ids)
                .ne("goods_propgroup_status", 2));

        if (ids.size() != list.size())
            throw new GoodsFiledException(CodeEnum.GOODS_PROP_GROUP_DELETE_FAIL_1.getMessage(), CodeEnum.GOODS_PROP_GROUP_DELETE_FAIL_1.getCode());

        for (GoodsPropgroup goodsPropgroup : list) {
            goodsPropgroup.setGoodsPropgroupStatus(2);
        }
        return updateBatchById(list);
    }


}
